<template>
  <a-modal
    v-model:open="visible"
    title="添加学员"
    ok-text="确认"
    cancel-text="取消"
    centered
    :width="484"
    :maskClosable="false"
    :okButtonProps="{ loading: loading }"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <div v-if="init" class="float-left text-center mt-30">
      <a-spin />
    </div>

    <div v-else class="float-left mt-24">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 7 }"
        :wrapper-col="{ span: 17 }"
      >
        <!-- 学员头像 -->
        <a-form-item
          label="学员头像"
          name="avatar"
          :rules="[{ required: true, message: '请上传学员头像!' }]"
        >
          <div class="d-flex">
            <img v-if="avatar" class="form-avatar mr-16" :src="avatar" />
            <UploadImageButton text="更换头像" @selected="handleAvatarChange" />
          </div>
        </a-form-item>

        <!-- 学员姓名 -->
        <a-form-item label="学员姓名" name="name">
          <a-input
            v-model:value="formState.name"
            style="width: 274px"
            placeholder="请填写学员姓名"
          />
        </a-form-item>

        <!-- 登录邮箱 -->
        <a-form-item label="登录邮箱" name="email">
          <a-input
            v-model:value="formState.email"
            allow-clear
            autocomplete="off"
            style="width: 274px"
            placeholder="请输入登录邮箱"
          />
        </a-form-item>

        <!-- 登录密码 -->
        <a-form-item label="登录密码" name="password">
          <a-input-password
            v-model:value="formState.password"
            allow-clear
            autocomplete="off"
            style="width: 274px"
            placeholder="请输入登录密码"
          />
        </a-form-item>

        <!-- 所属部门 -->
        <a-form-item label="所属部门" name="dep_ids">
          <a-tree-select
            v-model:value="formState.dep_ids"
            style="width: 274px"
            :tree-data="departments"
            tree-default-expand-all
            allow-clear
            multiple
            placeholder="请选择学员所属部门"
          />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { message } from "ant-design-vue";
import { user, department } from "@/api";
import UploadImageButton from "@/components/Common/upload-image-button.vue";
import memberDefaultAvatar from "@/assets/thumb/avatar.png";
import { useSystemStore } from "@/store";

interface PropInterface {
  open: boolean;
  depIds: any[];
  onCancel: () => void;
}

const props = defineProps<PropInterface>();
const emit = defineEmits(["update:open", "cancel"]);

const formRef = ref();
const init = ref(true);
const loading = ref(false);
const departments = ref<any[]>([]);
const avatar = ref<string>(memberDefaultAvatar);
const visible = ref(props.open);

const formState = reactive({
  email: "",
  name: "",
  password: "",
  avatar: -1,
  idCard: "",
  dep_ids: [] as any[],
});

// 表单校验规则
const rules = {
  name: [{ required: true, message: "请输入学员姓名!" }],
  email: [{ required: true, message: "请输入登录邮箱!" }],
  password: [{ required: true, message: "请输入登录密码!" }],
  dep_ids: [{ required: true, message: "请选择学员所属部门!" }],
};

// store
const systemConfig = useSystemStore();

watch(
  () => props.open,
  (val) => {
    visible.value = val;
    if (val) {
      initForm();
      getDepartments();
    }
  },
  { immediate: true }
);

const initForm = () => {
  formState.email = "";
  formState.name = "";
  formState.password = "";
  formState.avatar = systemConfig.memberDefaultAvatar ?? -1;
  formState.idCard = "";
  formState.dep_ids = props.depIds || [];

  if (systemConfig.memberDefaultAvatar === -1) {
    avatar.value = memberDefaultAvatar;
  } else if (systemConfig.memberDefaultAvatar >= 0) {
    avatar.value =
      systemConfig.resourceUrl?.[Number(systemConfig.memberDefaultAvatar)] ??
      memberDefaultAvatar;
  } else {
    avatar.value = memberDefaultAvatar;
  }
};

const getDepartments = () => {
  init.value = true;
  department.departmentList({}).then((res: any) => {
    const deps = res.data.departments;
    if (JSON.stringify(deps) !== "{}") {
      departments.value = buildTree(deps, 0);
    }
    init.value = false;
  });
};

const buildTree = (deps: any, id: number) => {
  const arr: any[] = [];
  for (let i = 0; i < deps[id]?.length || 0; i++) {
    const item = deps[id][i];
    if (!deps[item.id]) {
      arr.push({ label: item.name, value: item.id });
    } else {
      arr.push({
        label: item.name,
        value: item.id,
        children: buildTree(deps, item.id),
      });
    }
  }
  return arr;
};

const handleAvatarChange = (url: string, id: number) => {
  avatar.value = url;
  formState.avatar = id;
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    loading.value = true;
    await user.storeUser(
      formState.email,
      formState.name,
      formState.avatar,
      formState.password,
      formState.idCard,
      formState.dep_ids
    );
    message.success("保存成功！");
    handleCancel();
  } catch (e) {
    console.error("提交失败", e);
  } finally {
    loading.value = false;
  }
};

const handleCancel = () => {
  emit("cancel");
  emit("update:open", false);
};
</script>

<style scoped>
.form-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
</style>
